package com.pinecone.controller;

import com.alibaba.fastjson.JSONObject;
import com.pinecone.common.utils.HttpClientUtils;
import com.yunpian.sdk.util.JsonUtil;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hushangjie on 2017/10/19.
 */
@Controller
@RequestMapping("/oauth")
public class OauthController {
    @Autowired
    private RestTemplate restTemplate;
    //微博oauth2.0认证
    @RequestMapping(value = "/weibo",method = RequestMethod.GET)
    public Object weiboAuth(@RequestParam(value = "code",required = true) String code,
                            @RequestParam(value = "state",required = true) String state,
                            RedirectAttributesModelMap model){
        //通过code获取token
        String urlToGetToken = "https://api.weibo.com/oauth2/access_token?client_id=2725134099&client_secret=112c2cf04060b27d1a0fbb6f5ecdda0d&grant_type=authorization_code&redirect_uri=http://www.jackhoo.cn/oauth/weibo&code="+code;
        JSONObject tokenObject = HttpClientUtils.httpPost(urlToGetToken,"");
        model.put("uid",tokenObject.getString("uid"));
        model.put("access_token",tokenObject.getString("access_token"));
        model.put("user_type","weibo");
        return "redirect:"+state.substring(state.indexOf("live")-1,state.length());
    }
    //QQ oauth2.0认证
    @RequestMapping(value = "/qq",method = RequestMethod.GET)
    public Object qqAuth(@RequestParam(value = "code",required = true) String code,
                         @RequestParam(value = "state",required = true) String state,
                         RedirectAttributesModelMap model){
        //通过code获取token
        String urlToGetToken = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101431637&client_secret=05000a21f497b162f097d31828967505&redirect_uri=http://www.jackhoo.cn/oauth/qq&code="+code;
        String tokenObject = restTemplate.getForObject(urlToGetToken, String.class, "");
        Map<String,Object> token = analysisToken(tokenObject);

        model.put("access_token",token.get("access_token"));
        //通过token获取openId
        String urlToGetOpenId = "https://graph.qq.com/oauth2.0/me?access_token="+token.get("access_token");
        String openIdObject = restTemplate.getForObject(urlToGetOpenId, String.class, "");
        Map<String, String> openId = analysisOpenId(openIdObject);
        model.put("uid",openId.get("openid"));
        model.put("user_type","qq");

        return "redirect:"+state.substring(state.indexOf("live")-1,state.length());
    }
    private Map<String, Object> analysisToken(String tokenStr) {

        Map<String, Object> map = new HashMap<String, Object>(3);

        if (tokenStr != null && tokenStr.indexOf("&") >= 0) {

            String[] sv = tokenStr.split("&");
            Arrays.stream(sv).forEach(s -> {

                if (tokenStr != null && s.indexOf("=") >= 0) {
                    int index = s.lastIndexOf("=");
                    map.put(s.substring(0, index), s.substring(index + 1));
                }

            });

        }

        return map;
    }
    private Map<String, String> analysisOpenId(String openStr) {

        Map<String, String> map = new HashMap<String, String>(3);

        if (openStr != null && openStr.replaceAll(" ", "").startsWith("callback") && openStr.indexOf("{")>=0 && openStr.indexOf("}") >=0) {
            int begin = openStr.indexOf("{");
            int end = openStr.indexOf("}")+1;

            String string = openStr.substring(begin, end);
            try {
                map = JsonUtil.fromJsonToMap(string);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return map;
    }
}
